# from django.shortcuts import render
from django.views import View

from topic.models import Topic
from user.models import UserProfile

from utils.return_data import resultError, resultSuccess
import json



class TopicView(View):
    def get(self, request, username):
        try:
            user = UserProfile.objects.get(username=username)
        except Exception as e:
            return resultError('111', '用户查询异常')

        topics = Topic.objects.values().filter(author=user)

        result_data = {
            'nickname': user.nickname,
            'topics': list(topics)
        }

        print(result_data)

        return resultSuccess('200', '获取列表成功', result_data)

    def post(self, request, username):
        print(request.body)
        json_str = request.body
        json_obj = json.loads(json_str)

        title = json_obj['title']
        category = json_obj['category']
        limit = json_obj['limit']
        content = json_obj['title']
        introduce = content[: 20]

        Topic.objects.create(title=title, category=category,
                             limit=limit, content=content,
                             author=UserProfile.objects.get(username=username),
                             introduce=introduce)
        return resultSuccess("200", 'success')
